<?php
class ApiCenter_ProductApi_Model_Api2_Product_Save_Rest_Admin_V1 extends  ApiCenter_ProductApi_Model_Api2_Product_Save_Rest{
    
    protected  $result= array(); 
    
    protected  function _update($filteredData){
        

         $res= array();
        $product_id = $vendorId  = $this->getRequest()->getParam("id");
        try{
            $vendorId  = $this->getRequest()->getParam("vendorid");
        
            $this->_loadVendor($vendorId);
             
            $product = $filteredData['product']['data'];
        
            $type = $product['type_id'];
        
            $set = $product['set_id'];
        
            //验证类型
            $this->_checkProductTypeExists($type);
            //验证属性集
            $this->_checkProductAttributeSet($set);
        
            if($type=="simple"){
                $res =  $this->uploadSimple($product,$type,$set);//上传简单产品
            }elseif ($type=="configurable"){
                $res = $this->uploadConfigurable($product,$type,$set);
            }
        }catch (Exception $e){
            Mage::log("最终捕获到错误");
            Mage::log($e->getMessage());
            $res['status'] = 0;
            $res['info'] = $e->getMessage();
        }
        $this->_render($res);         
        
        }
       
    
    protected  function  _multiUpdate($filteredData){
        $res= array();
        /*
         * 创建产品流程
         * 
         *1. 判断传过来的数据类型。首先判断传过来产品的数据类型  simple or configurable
         *   如果是组合产品 至少要创建两个以上产品  并将组产品的通用属性添加到子产品的属性当中去
         *2. 对数据进行验证。 ①必填项需要填写②数据格式是否按要求传送
         *3. 对商家数据进行默认处理。①组产品自有的子产品数据的创建
         *4. 将数据进行于保存处理和验证。
         *5. 上传。
         *
         *组产品与
         * */
        try{
            $vendorId  = $this->getRequest()->getParam("vendorid");
            
             $this->_loadVendor($vendorId);
            
            Mage::log($filteredData,1,"upload.log");
            
            $product = $filteredData['product']['data'];
            
            $type = $product['type_id'];
            
            $set = $product['set_id'];
            
            //验证类型
            $this->_checkProductTypeExists($type);
            //验证属性集
            $this->_checkProductAttributeSet($set);
            
            if($type=="simple"){    
                $res =  $this->uploadSimple($product,$type,$set);//上传简单产品
            }elseif ($type=="configurable"){
                $res = $this->uploadConfigurable($product,$type,$set);
            }
 
        }catch (Exception $e){
            Mage::log("最终捕获到错误");
            Mage::log($e->getMessage());
            $res['status'] = 0;
            $res['info'] = $e->getMessage();
        } 
        $this->_render($res);
    }
    
    /**
     *  添加配置商品
     *
     *
     **/
     
        public function uploadConfigurable($productData,$type,$set){
            $edit = $this->getRequest()->getParam("id",null);
            $select_super = array();
            $Skus = array();
            
            $attr_price    =$productData['price_setting'];
            try {
                    if (empty($attr_price)){
                        $this->_critical("请设置子产品的价格",400);
                    }
                    if(empty($productData['child_products'])){
                        $this->_critical("子产品必须大于至少一个",400);
                    }
                    if($edit&&$productData['deleteChilds']){
                        $this->deleteProduct($productData['deleteChilds']);
                        unset($productData['deleteChilds']);
                    }
                    foreach ($productData['child_products'] as $val){
                            if(empty($val['entity_id'])){
                                $Skus[] =$val['vendor_sku'];
                            }
                    }
                    $vendorid = Mage::registry("current_vendor")->getVendorId();
                    
                    if(empty($edit)){
                        $Skus[] =  $productData['vendor_sku'];
                     }
           
                 $this->_checkSkuExists($Skus, $vendorid);
                    /* @var $helper ApiCenter_ProductApi_Helper_Data */
                    $helper =Mage::helper("productapi");
                    $attr_collection = Mage::getResourceModel('catalog/product_attribute_collection')
                    ->setAttributeSetFilter($set)
                    ->addfieldtofilter("is_global",1)
                    ->addfieldtofilter("frontend_input",'select')
                    ->addfieldtofilter("is_configurable",1)
                    ->addVisibleFilter()
                    ->load();
                   
                foreach ($attr_collection as $attr){
                            $set_superattr[] = $attr->getAttributeCode();            
                }
                
                foreach ($productData['child_products'] as $child){
                        foreach ($child as $key=>$val){
                            if(in_array($key, $set_superattr)){
                                $select_supers[$key]=1;
                            }
                        }
                }
                foreach ($select_supers as $super => $num){
                        $select_super[] =$super;
                }
                $childProduct =  $this->_automaticallyChildPro($productData,$select_super);
                $transaction = Mage::getModel('core/resource_transaction');
             //   if(count($childProduct)>1){
                    foreach ($childProduct as  $key => $product){
                        //返回子产片所有的id
                        $model= $this->saveProduct('simple',$set,$product);      
						$product_models[] = $model;
                        $transaction->addObject($model);
                    }
                    try {
                        foreach ($product_models as $_cmodel){
                            $_cmodel->validate();
                        }
                    } catch (Exception $e) {
                        $this->_critical("产品信息有误，请检查后重试！", 400);
                    }
                    try {	
                        $transaction->save();
                    } catch (Exception $e) {
                        $this->_critical("产品保存失败，请重试！" ,400);
                    }	
                    foreach ($product_models as $_model){
                        $simpleProductIds[] = $_model->getId();
                    }
                    //销毁模型变量
                    $product_models= null;
                    unset($product_models);
//                 }else{
//                        $product = $childProduct[0];
//                        $model = $this->saveProduct('simple',$set,$product); 
//                        $transaction->addObject($model);
//                        try {
//                            $transaction->save();
//                        } catch (Exception $e) {
//                            Mage::log("组产品最终保存失败",1,"upload.log");
//                            $this->_critical("产品保存失败！" ,400);
//                        }	
                       
//                        $simpleProductIds[] = $model->getId();
//                 }
                //销毁模型变量
                $transaction=null;
                unset($transaction);
                //此处捕获异常是为了 在组产品创建失败后立即删除已经创建子产品
                try {
                    $productDataInfo = $this->getConfigAttrCode($set,$select_super,$simpleProductIds,$product['price_setting']);
                    
                    Mage::log("返回配置好的的组合数据",1,"upload.log");
                    Mage::log($productDataInfo,1,"upload.log");
                    
                    //获得所有子产品的重量
                    $Weights =array();
                    //此处变量在处理子产品的函数里生成
                    $Weights = Mage::registry("childweight");
                    Mage::unregister('childweight');
                     if($Weights){
                         $productData['common_weight'] = max($Weights);
                     }
               
                    $productData['configurable_attributes_data']=$productDataInfo['configurable_attributes_data'];
                    $productData['configurable_products_data']=$productDataInfo['configurable_products_data'];
                    $productData['can_save_configurable_attributes'] = true;
                    $configurableSetId =$productData['set_id'];
                    unset($productData['child_product']);
                    unset($productData['price_setting']);
                    
                    $configModel =  $this->saveProduct($type,$set,$productData);
//                     try {
//                         $configModel->validate();
//                     } catch (Exception $e) {
//                         $this->_critical("产品信息有误，请检查后重试！", 400);
//                         $this->deleteProduct($simpleProductIds);
//                     }
                    try {
                        $configModel->save();
                    } catch (Exception $e) {
                        Mage::log("组产品保存最终失败" ,1,"upload.log");
                        if(!$edit){
                          $this->deleteProduct($simpleProductIds);
                        }
                        $this->_critical("产品保存失败，请重试！" ,400);
                    }
                } catch (Exception $e) { 
                        if(!$edit){
                            $this->deleteProduct($simpleProductIds);
                        }
                        $this->deleteProduct($simpleProductIds);
                        Mage::log("组产品创建过程中失败" ,1,"upload.log");
                        $this->_critical("产品保存失败，请重试！" ,400);
                }
                $this->result['status'] = "1";
                $this->result['info'] = "上传成功";
                } catch (Exception $e) {
                   Mage::log("可配置数据产品出错",1,"upload.log");
                   Mage::log($e->getMessage(),1,"upload.log");
                   $this->result['status'] = "0";
                   $this->result['info'] =$e->getMessage();
                }
                Mage::log($this->result);
                return  $this->result;
        }
        
            /**
             * 添加简单类型的产品
             * */
            public function uploadSimple($productData,$type,$set){
                try {
                    /* @var $helper ApiCenter_ProductApi_Helper_Data */
//                     $helper =Mage::helper("productapi");
                         $this->result['status'] = "1";
                         $model = $this->saveProduct('simple',$set,$productData);
                         try {
                             $model->validate();
                         } catch (Exception $e) {
                             $this->_critical("产品信息有误，请检查后重试,！", 400);
                         }
                         try {
                             $model->save();
                         } catch (Exception $e) {
                             Mage::log("单保存最终失败" ,1,"upload.log");
                             $this->_critical("产品保存失败，请重试！" ,400);
                         }
                         $this->result['status'] = "1";
                        $this->result['info']= "产品上传成功!";
                } catch (Exception $e) {
                        $this->result['status'] = "0";
                        $this->result['info'] = $e->getMessage();
                   
                }
                return $this->result;
            }
            
            protected function deleteProduct($productIds){
                
                if(!empty($productIds)){
                    try{
                        
                        foreach ($productIds as $_productId){
                            $product = Mage::getSingleton('catalog/product')->load($_productId);
                            Mage::log($product->getSku(),1,"deleteproduct.log");
                            $product->delete();
                        }
                    }catch(Exception $e) {
                        Mage::log("子产品产品删除失败:".$_productId);
                        }
                      
                    }
                }
            
}